package com.itheima.filter;

import com.itheima.util.JwtUtils;
import io.jsonwebtoken.Claims;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class LonginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        // 如果本次请求路径  不在拦截范围内：直接放行
        String uri = req.getRequestURI();
        if("/login".equals(uri)){
            filterChain.doFilter(servletRequest, servletResponse);
            return;

        }
       // 如果已经登录，那么后端必定给客户端token,客户端请求时必定会携带 token。如果没有token，那么一定是未登录
       String token = req.getHeader("token");
        if (token == null || token.equals("")){
            // 如果没有登录：如果没有登录，就禁止放行（不放行）：通常设置状态码为 401，表示未认证登录UNAUTHORIZED
            resp.setStatus(401);

            return;
        }
        // 如果有token，那么就进行解析,如果发现令牌过期或被篡改，不能放行
        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            resp.setStatus(401);
            return;
        }
        // 有令牌且令牌没有过期，那么就放行
        filterChain.doFilter(servletRequest, servletResponse);


    }
}
